import axios from "~/axios.js";
export function loginApi(data) {
   return  axios.post('/api/auth/login',data)
}
export function registerApi(data) {
   return axios.post('/api/registration/register',data)
}
export function getVerificationCode(data) {
   return axios.post('/api/requestVerificationCode',data)
}

export function setCookie(name, value, days) {
   const expires = new Date(Date.now() + days * 864e5).toUTCString();
   document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=/';
}

export function getCookie(name) {
   return document.cookie.split('; ').reduce((r, v) => {
      const parts = v.split('=');
      if (parts[0] === name) {
         let value = decodeURIComponent(parts[1]);
         // 去掉前后的双引号
         value = value.replace(/^"|"$/g, '');
         return value;
      }
      return r;
   }, '');
}

export function deleteCookie(name) {
   setCookie(name, '', -1); // 设置过期时间为过去
}

export function parseJwt(token) {
   if(token == undefined || token == null) {
      console.error('Token is undefined');
      return
   }
   if (typeof token !== 'string') {
      throw new TypeError('Expected a string for the token');
   }
   const base64Url = token.split('.')[1];
   const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
   const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
   }).join(''));

   return JSON.parse(jsonPayload);
}


